package com.platform.destiny.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.platform.destiny.dto.Result;
import com.platform.destiny.dto.UserDto;
import com.platform.destiny.utils.JwtUtils;
import com.platform.destiny.utils.ResponseUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 认证成功处理器
 *
 * @Description
 * @Author kaiyang
 * @Date 2024-01-17 11:08 上午
 */

@Slf4j
@Component
public class AppSuccessHandler implements AuthenticationSuccessHandler {

    @Autowired
    private ObjectMapper objectMapper;


    @Override
    public void onAuthenticationSuccess(HttpServletRequest request,
                                        HttpServletResponse response, Authentication auth) throws IOException, ServletException {



        String contentType = request.getContentType();
        log.info("content type is {} 登录成功!", contentType);
        response.setStatus(HttpStatus.OK.value());
        response.setContentType("application/json;charset=UTF-8");
        response.setCharacterEncoding("UTF-8");
        // 可以返回 认证信息，也可以返回登录成功页面
        UserDto dto = (UserDto) auth.getPrincipal();
        String token = JwtUtils.createToken(dto);
        Result<String> result = Result.success(token);
        ResponseUtils.response(response, result);

        // response.getWriter().write(objectMapper.writeValueAsString(auth));
        // 转发地址
        // response.sendRedirect();

        // request.getRequestDispatcher("/url").include(request,response);
        // request.getRequestDispatcher("/url").forward(request,response);
        // request.sendRedirect("/url");


    }


}
